<template>
    <div class="crm-contract-info-container">
        <el-drawer title="合同详情" v-model="isShowDialog" size="85%" :close-on-click-modal="false">
            <el-tabs v-model="activeName" class="contract-detail ml15">
                <el-tab-pane label="合同详情" name="contract">
                    <el-descriptions :column="4" border>
                        <el-descriptions-item label="合同编号">{{ contract.contractCode }}</el-descriptions-item>
                        <el-descriptions-item label="合同名称">{{ contract.contractName }}</el-descriptions-item>
                        <el-descriptions-item label="合同类型">{{ getDictionaryText('crm_contract_type', contract.contractType) }}</el-descriptions-item>
                        <el-descriptions-item label="到期状态">{{ expiryStatusText(contract.expiryStatus) }}</el-descriptions-item>

                        <el-descriptions-item label="合同金额">{{ contract.contractAmount }}元</el-descriptions-item>
                        <el-descriptions-item label="总回款金额">{{ contract.totalReceivable }}元</el-descriptions-item>
                        <el-descriptions-item label="待回款金额">{{ contract.awaitReceivable }}元</el-descriptions-item>
                        <el-descriptions-item label="总支出金额">{{ contract.totalExpense }}元</el-descriptions-item>

                        <el-descriptions-item label="总利润金额">{{ contract.totalProfit }}元</el-descriptions-item>
                        <el-descriptions-item label="净利润金额">{{ contract.grossProfit }}元</el-descriptions-item>
                        <el-descriptions-item label="开始时间">{{ contract.contractStartTime }}</el-descriptions-item>
                        <el-descriptions-item label="结束时间">{{ contract.contractEndTime }}</el-descriptions-item>

                        <el-descriptions-item label="签约日期">{{ contract.signDate }}</el-descriptions-item>
                        <el-descriptions-item label="客户名称">{{ contract.customerName }}</el-descriptions-item>
                        <el-descriptions-item label="企业名称">{{ contract.enterpriseName }}</el-descriptions-item>
                        <el-descriptions-item label="签约人">{{ contract.signerName }}</el-descriptions-item>

                        <el-descriptions-item label="负责人">{{ contract.ownerName }}</el-descriptions-item>
                        <el-descriptions-item label="审核状态">{{ examineStatusText(contract.examineStatus) }}</el-descriptions-item>
                        <el-descriptions-item label="业务类型">
                            <el-tag class="mr10" v-for="category in contract?.categorys" :key="category">{{ category.name }}</el-tag>
                        </el-descriptions-item>
                    </el-descriptions>
                    <el-descriptions class="mt15" :column="4" border>
                        <el-descriptions-item label="创建者">{{ contract.createBy }}</el-descriptions-item>
                        <el-descriptions-item label="创建时间">{{ contract.createTime }}</el-descriptions-item>
                        <el-descriptions-item label="更新者">{{ contract.updateBy }}</el-descriptions-item>
                        <el-descriptions-item label="更新时间">{{ contract.updateTime }}</el-descriptions-item>
                        
                        <el-descriptions-item label="所属用户">{{ contract.userName }}</el-descriptions-item>
                        <el-descriptions-item label="所属部门">{{ contract.deptName }}</el-descriptions-item>
                        <el-descriptions-item label="备注">{{ contract.remark }}</el-descriptions-item>
                    </el-descriptions>
                    <el-carousel class="mt15" height="800px" :autoplay="false" v-if="contract.attachments && contract.attachments.length > 0">
                        <el-carousel-item v-for="item in contract.attachments" :key="item">
                            <center>
                                <template v-if="item.url.toLowerCase().endsWith('.pdf')">
                                    <iframe :src="getStorageAccessTokenUrl(item.url)" width="100%" height="800px" frameborder="0"></iframe>
                                </template>
                                <template v-else>
                                    <el-image style="max-width: auto; height: 800px;" :src="getStorageAccessTokenUrl(item.url)" fit="contain" />
                                </template>
                            </center>
                        </el-carousel-item>
                    </el-carousel>
                </el-tab-pane>
                <el-tab-pane label="项目详情" name="projects">
                    <el-table :data="contract.projects" style="width: 100%" row-key="id">
                        <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                        <el-table-column label="项目名称" prop="projectName" show-overflow-tooltip></el-table-column>
                        <el-table-column label="项目状态" prop="projectStatus" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-if="scope.row.projectStatus == '0'" class="color-info">未开始</span>
                                <span v-else-if="scope.row.projectStatus == '1'" class="color-primary">进行中</span>
                                <span v-else-if="scope.row.projectStatus == '1'" class="color-success">已完成</span>
                                <span v-else class="color-warning">已暂停</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="开始时间" prop="projectStartTime" show-overflow-tooltip></el-table-column>
                        <el-table-column label="结束时间" prop="projectEndTime" show-overflow-tooltip></el-table-column>
                        <el-table-column label="完成时间" prop="finishTime" show-overflow-tooltip></el-table-column>
                        <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip></el-table-column>
                        <el-table-column label="操作" show-overflow-tooltip width="80" v-auths="['crm:project:info']">
                            <template #default="scope">
                                <el-button v-auth="'crm:project:info'" type="primary" link @click="onOpenInfoCrmProject(scope.row)">详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="回款详情" name="receivable"> 
                    <el-table :data="contract.receivables" style="width: 100%" row-key="id">
                        <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                        <el-table-column label="回款主题" prop="receivableName" show-overflow-tooltip></el-table-column>
                        <el-table-column label="客户名称" prop="customerName" show-overflow-tooltip></el-table-column>
                        <el-table-column label="回款日期" prop="paymentTime" show-overflow-tooltip></el-table-column>
                        <el-table-column label="回款方式" prop="paymentMethod" show-overflow-tooltip :formatter="loadPaymentMethod"></el-table-column>
                        <el-table-column label="回款金额" prop="paymentAmount" show-overflow-tooltip>
                            <template #default="scope">
                                <span>{{scope.row.paymentAmount}} 元</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="是否开票" prop="hasInvoice" show-overflow-tooltip>
                            <template #default="scope">
                                <span class="color-primary" v-if="scope.row.hasInvoice">是</span>
                                <span class="color-info" v-else>否</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="审核状态" prop="examineStatus" width="80" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-if="scope.row.examineStatus == '0'" class="color-primary">草稿</span>
                                <span v-else-if="scope.row.examineStatus == '1'" class="color-warning">审核中</span>
                                <span v-else-if="scope.row.examineStatus == '2'" class="color-success">通过</span>
                                <span v-else-if="scope.row.examineStatus == '3'" class="color-danger">驳回</span>
                                <span v-else-if="scope.row.examineStatus == '4'" class="color-primary">撤回</span>
                                <span v-else-if="scope.row.examineStatus == '5'" class="color-info">作废</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip></el-table-column>
                        <el-table-column label="操作" show-overflow-tooltip width="80" v-auths="['crm:receivable:info']">
                            <template #default="scope">
                                <el-button v-auth="'crm:receivable:info'" type="primary" link @click="onOpenInfoCrmReceivable(scope.row)">详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="支出详情" name="expenses"> 
                    <el-table :data="contract.expenses" style="width: 100%" row-key="id">
                        <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                        <el-table-column label="支出主题" prop="expenseName" show-overflow-tooltip></el-table-column>
                        <el-table-column label="申请人" prop="ownerName" show-overflow-tooltip></el-table-column>
                        <el-table-column label="支出金额" prop="expenseAmount" show-overflow-tooltip>
                            <template #default="scope">
                                <span>{{scope.row.expenseAmount}} 元</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="申请日期" prop="expenseTime" show-overflow-tooltip></el-table-column>
                        <el-table-column label="是否开票" prop="hasInvoice" show-overflow-tooltip>
                            <template #default="scope">
                                <span class="color-primary" v-if="scope.row.hasInvoice">是</span>
                                <span class="color-info" v-else>否</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="审核状态" prop="examineStatus" width="80" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-if="scope.row.examineStatus == '0'" class="color-primary">草稿</span>
                                <span v-else-if="scope.row.examineStatus == '1'" class="color-warning">审核中</span>
                                <span v-else-if="scope.row.examineStatus == '2'" class="color-success">通过</span>
                                <span v-else-if="scope.row.examineStatus == '3'" class="color-danger">驳回</span>
                                <span v-else-if="scope.row.examineStatus == '4'" class="color-primary">撤回</span>
                                <span v-else-if="scope.row.examineStatus == '5'" class="color-info">作废</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip></el-table-column>
                        <el-table-column label="操作" show-overflow-tooltip width="80" v-auths="['crm:expense:info']">
                            <template #default="scope">
                                <el-button v-auth="'crm:expense:info'" type="primary" link @click="onOpenInfoCrmExpense(scope.row)">详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="发票详情" name="invoices">
                    <el-table :data="contract.invoices" style="width: 100%" row-key="id">
                        <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                        <el-table-column label="发票类型" width="150" prop="invoiceType" show-overflow-tooltip :formatter="loadInvoiceType"></el-table-column>
                        <el-table-column label="抬头类型" width="100" prop="invoiceTitleType" show-overflow-tooltip :formatter="loadInvoiceTitle"></el-table-column>
                        <el-table-column label="开票抬头" width="250" prop="invoiceTitle" show-overflow-tooltip></el-table-column>
                        <el-table-column label="发票代码" width="150" prop="invoiceCode" show-overflow-tooltip></el-table-column>
                        <el-table-column label="发票号码" width="150" prop="invoiceNumber" show-overflow-tooltip></el-table-column>
                        <el-table-column label="发票金额" width="150" prop="invoiceAmount" show-overflow-tooltip>
                            <template #default="scope">
                                <span>{{scope.row.invoiceAmount}} 元</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="开票日期" width="100" prop="invoiceDate" show-overflow-tooltip></el-table-column>
                        <el-table-column label="购方开户行" width="200" prop="buyerDepositBank" show-overflow-tooltip></el-table-column>
                        <el-table-column label="购方开户账户" width="200" prop="buyerDepositAccount" show-overflow-tooltip></el-table-column>
                        <el-table-column label="购方纳税识别号" width="200" prop="buyerTaxNumber" show-overflow-tooltip></el-table-column>
                        <el-table-column label="购方开户地址" width="200" prop="buyerDepositAddress" show-overflow-tooltip></el-table-column>
                        <el-table-column label="购方联系电话" width="200" prop="buyerTelephone" show-overflow-tooltip></el-table-column>
                        <el-table-column label="销方开户行" width="200" prop="sellerDepositBank" show-overflow-tooltip></el-table-column>
                        <el-table-column label="销方开户账户" width="200" prop="sellerDepositAccount" show-overflow-tooltip></el-table-column>
                        <el-table-column label="销方开户地址" width="200" prop="sellerDepositAddress" show-overflow-tooltip></el-table-column>
                        <el-table-column label="纳税识别号" width="200" prop="sellerTaxNumber" show-overflow-tooltip></el-table-column>
                        <el-table-column label="销方联系电话" width="200" prop="sellerTelephone" show-overflow-tooltip></el-table-column>
                        <el-table-column label="审核状态" prop="examineStatus" width="80" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-if="scope.row.examineStatus == '0'" class="color-primary">草稿</span>
                                <span v-else-if="scope.row.examineStatus == '1'" class="color-warning">审核中</span>
                                <span v-else-if="scope.row.examineStatus == '2'" class="color-success">通过</span>
                                <span v-else-if="scope.row.examineStatus == '3'" class="color-danger">驳回</span>
                                <span v-else-if="scope.row.examineStatus == '4'" class="color-primary">撤回</span>
                                <span v-else-if="scope.row.examineStatus == '5'" class="color-info">作废</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="创建时间" width="180" prop="createTime" show-overflow-tooltip></el-table-column>
                        <el-table-column label="操作" fixed show-overflow-tooltip width="80" v-auths="['crm:invoice:info']">
                            <template #default="scope">
                                <el-button v-auth="'crm:invoice:info'" type="primary" link @click="onOpenInfoCrmInvoice(scope.row)">详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane> 
                <el-tab-pane label="记账详情" name="accounts" v-if="contract.contractType == '2'">
                    <el-table :data="contract.accounts" style="width: 100%" row-key="id">
                        <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                        <el-table-column label="账期序号" prop="periodNum" width="80" show-overflow-tooltip></el-table-column>
                        <el-table-column label="记账主题" prop="title" width="300" show-overflow-tooltip></el-table-column>
                        <el-table-column label="记账类型" prop="accountType" width="100" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-if="scope.row.accountType == 'D'" class="color-success">按天</span>
                                <span v-if="scope.row.accountType == 'W'" class="color-warning">按周</span>
                                <span v-if="scope.row.accountType == 'M'" class="color-primary">按月</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="开始时间" prop="accountStartTime" width="150" show-overflow-tooltip></el-table-column>
                        <el-table-column label="结束时间" prop="accountEndTime" width="150" show-overflow-tooltip></el-table-column>
                        <el-table-column label="申报状态" prop="reportStatus" width="100" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-if="scope.row.reportStatus == '0'" class="color-danger">未申报</span>
                                <span v-if="scope.row.reportStatus == '1'" class="color-success">已申报</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="税种名称" prop="taxation" width="180" show-overflow-tooltip></el-table-column>
                        <el-table-column label="开票数量" prop="invoiceNum" width="80" show-overflow-tooltip></el-table-column>
                        <el-table-column label="所属用户" prop="userName" width="100" show-overflow-tooltip></el-table-column>
                        <el-table-column label="所属部门" prop="deptName" width="200" show-overflow-tooltip></el-table-column>
                        <el-table-column label="创建时间" prop="createTime" width="180" show-overflow-tooltip></el-table-column>
                        <el-table-column label="操作" fixed="right" show-overflow-tooltip width="80" v-auths="['crm:contract:account:info']">
                            <template #default="scope">
                                <el-button v-auth="'crm:contract:account:info'" type="primary" link @click="onOpenInfoCrmContractAccount(scope.row)">详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="审核记录时间线" name="examineRecord">
                    <el-timeline>
                        <el-timeline-item
                            v-for="(item, index) in contract?.examineRecord?.examineLoggers"
                            :key="index"
                            :timestamp="item.examineTime"
                            placement="top"
                        >
                            <el-row>
                                <el-col :span="6"><strong>审核人：</strong>{{ item.examineUserName }}</el-col>
                                <el-col :span="6"><strong>审核状态：</strong>{{ examineStatusText(item.examineStatus) }}</el-col>
                                <el-col :span="6"><strong>审核原由：</strong>{{ item.examineReason || '无' }}</el-col>
                            </el-row>
                        </el-timeline-item>
                    </el-timeline>
                </el-tab-pane>
            </el-tabs>
        </el-drawer>
        <InfoCrmReceivable ref="infoCrmReceivableRef"></InfoCrmReceivable>
        <InfoCrmExpense ref="infoCrmExpenseRef"></InfoCrmExpense>
        <InfoCrmProject ref="infoCrmProjectRef"></InfoCrmProject>
        <InfoCrmInvoice ref="infoCrmInvoiceRef"></InfoCrmInvoice>
        <InfoCrmContractAccount ref="infoCrmContractAccountRef"></InfoCrmContractAccount>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { Session } from '/@/utils/storage';
import { getCrmContract } from '/@/api/crm/contract/index';
import { getDictionaryByLabel } from '/@/api/system/dictionary/index';
import InfoCrmReceivable from '/@/views/crm/receivable/infoCrmReceivable.vue';
import InfoCrmExpense from '/@/views/crm/expense/infoCrmExpense.vue';
import InfoCrmProject from '/@/views/crm/project/infoCrmProject.vue';
import InfoCrmInvoice from '/@/views/crm/invoice/infoCrmInvoice.vue';
import InfoCrmContractAccount from '/@/views/crm/contract/account/infoCrmContractAccount.vue';
export default {
    name: 'crm/contract/info',
    components: {
        InfoCrmReceivable,
        InfoCrmExpense,
        InfoCrmProject,
        InfoCrmInvoice,
        InfoCrmContractAccount,
    },
    setup(props, context) {
        const infoCrmReceivableRef = ref();
        const infoCrmExpenseRef = ref();
        const infoCrmProjectRef = ref();
        const infoCrmInvoiceRef = ref();
        const infoCrmContractAccountRef = ref();
        const state = reactive({
            isShowDialog: false,
            activeName: 'contract',
            contract: {
                accounts: [],
                invoices: [],
                receivables: [],
                expenses: [],
            },
            dictionary: new Map(),
        });

        const examineStatusText = (status: String) => {
            const statusMap = {
                '0': '草稿',
                '1': '审核中',
                '2': '通过',
                '3': '驳回',
                '4': '撤回',
                '5': '作废'
            };
            return statusMap[status] || '未知';
        };
        const getDictionaryText = (dictLabel: String, dictValue: String) => {
            const dictionarys = state.dictionary.get(dictLabel) || [];
            return dictionarys.find(item => item.dictValue == dictValue)?.dictName;
        };
        const expiryStatusText = (status: String) => {
            const statusMap = {
                '0': '未到期',
                '1': '即将到期',
                '2': '已到期',
                '3': '已续期',
                '4': '已结束'
            };
            return statusMap[status] || '未知';
        };

        // 打开弹窗
        const openDialog = (row?: object) => {
            state.isShowDialog = true;
            if(row){
                getCrmContract({id: row.id}).then((res) => {
                    if(res.code == 0){
                        state.contract = Object.assign({}, res.data);
                    }
                });
            }
            getDictionaryByLabel({ dictLabel: 'crm_contract_type' }).then((res: any) => {
                if (res.code == 0) {
                    state.dictionary.set('crm_contract_type', res.data);
                }
            });
            getDictionaryByLabel({ dictLabel: 'crm_payment_method' }).then((res: any) => {
                if (res.code == 0) {
                    state.dictionary.set('crm_payment_method', res.data);
                }
            });
            getDictionaryByLabel({ dictLabel: 'crm_invoice_type' }).then((res: any) => {
                if (res.code == 0) {
                    state.dictionary.set('crm_invoice_type', res.data);
                }
            });
            getDictionaryByLabel({ dictLabel: 'crm_invoice_title' }).then((res: any) => {
                if (res.code == 0) {
                    state.dictionary.set('crm_invoice_title', res.data);
                }
            });
        };
        // 关闭弹窗
        const closeDialog = (row?: object) => {
            state.isShowDialog = false;
            for(var key in state.formData) {
                state.formData[key] = undefined;
            }
        };

        const loadPaymentMethod = (row, column, cellValue, index) => {
            return getDictionaryText('crm_payment_method', cellValue);
        }

        const loadInvoiceType = (row, column, cellValue, index) => {
            return getDictionaryText('crm_invoice_type', cellValue);
        }

        const loadInvoiceTitle = (row, column, cellValue, index) => {
            return getDictionaryText('crm_invoice_title', cellValue);
        }
        
        const onOpenInfoCrmReceivable = (row: object) => {
            infoCrmReceivableRef.value.openDialog(row);
        };

        const onOpenInfoCrmExpense = (row: object) => {
            infoCrmExpenseRef.value.openDialog(row);
        };

        const onOpenInfoCrmProject = (row: object) => {
            infoCrmProjectRef.value.openDialog(row);
        };

        const onOpenInfoCrmInvoice = (row: object) => {
            infoCrmInvoiceRef.value.openDialog(row);
        };
        const onOpenInfoCrmContractAccount = (row: object) => {
            infoCrmContractAccountRef.value.openDialog(row);
        };
        const getStorageAccessTokenUrl = (url) => {
			return url + '?accessToken=' + Session.get('token');
		}

        return {
            infoCrmReceivableRef,
            infoCrmExpenseRef,
            infoCrmProjectRef,
            infoCrmInvoiceRef,
            infoCrmContractAccountRef,
            openDialog,
            closeDialog,
            examineStatusText,
            getDictionaryText,
            expiryStatusText,
            loadPaymentMethod,
            loadInvoiceType,
            loadInvoiceTitle,
            onOpenInfoCrmReceivable,
            onOpenInfoCrmExpense,
            onOpenInfoCrmProject,
            onOpenInfoCrmInvoice,
            onOpenInfoCrmContractAccount,
            getStorageAccessTokenUrl,
            ...toRefs(state),
        };
    },
};
</script>
<style scoped lang="scss">
.crm-contract-info-container {
    :deep .el-descriptions .is-bordered-label {
        width: 100px !important; /* 固定宽度为 100px */
    }
}
</style>